package com.config;

import com.mapper.living.UserDao;
import com.util.UserUtil;
import living.com.domain.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * <p>
 *     ip拦截器,只能网关对应的ip才可以访问
 * </p>
 * @author zdh
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RefreshScope
public class IpHandlerInterceptor extends HandlerInterceptorAdapter {
    private final UserDao userDao;
    private static final PasswordEncoder encoder=new BCryptPasswordEncoder();

    @Value("${enable}")
    public Boolean enable;

    @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     log.info("用户请求的ip {}",request.getRemoteAddr());
     log.info("当前enable的值为: {}",enable);
     if(enable)
     {
         log.info("访问拦截已经开启");
         //请求头中是否包含特殊标记
         String dhy = request.getHeader("dhy");
         if(dhy==null||!dhy.equals(encoder.encode("dhyLikeXpy")))
         {
             throw new IllegalArgumentException("非法访问");
         }
     }
     log.info("用户请求的资源 {}",request.getRequestURI());
     Integer u_id = Integer.valueOf(request.getHeader("u_id"));
     log.info("用户id {}",request.getHeader("u_id"));
     //查找对应用户是否存在
     User user = userDao.getUserById(u_id);
     log.info("用户名如下: {}",user.getUsername());
     UserUtil.setUser(user);
     return true;
 }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     //请求完毕,移除当前用户信息
      UserUtil.removeUser();
    }
}
